package com.pactera.miyuangroup.service.impl;

import com.alibaba.fastjson.JSON;
import com.pactera.miyuangroup.common.Constants;
import com.pactera.miyuangroup.common.RedisOperation;
import com.pactera.miyuangroup.config.CommonConfig;
import com.pactera.miyuangroup.service.ISmsService;
import com.pactera.miyuangroup.util.Date;
import com.pactera.miyuangroup.util.OkHttpUtils;
import com.pactera.miyuangroup.vo.SmsResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.*;

/**
 * 短信验证码
 *
 * @author Wangwu
 * @create 2018-05-15 上午11:43
 **/
@Service
@Slf4j
public class SmsServiceImp implements ISmsService {
    @Autowired
    private RedisOperation redis;
    @Autowired
    private CommonConfig common;


    @Override
    public SmsResult loginCode(String p) {
        SmsResult res = new SmsResult();
        String code = redis.get(Constants.REDIS_SMS_CODE + p, String.class, "");
        if (StringUtils.isBlank(code)) {
            code = UUID.randomUUID().toString().replace("-", "");
            code = code.substring(code.length() - 6, code.length());
            log.info("短信验证码：{}", code);
            res = Send(Arrays.asList(p), MessageFormat.format(common.getSms().getLoginMessageContent(), code));
            if (res.isSuccess()) {
                redis.set(Constants.REDIS_SMS_CODE + p, common.getSms().getEffectiveTime(), code.toUpperCase());
            }
        } else {
            res.setMsg("已发送，请勿重复发送");
            res.setSuccess(false);
        }
        return res;
    }


    /**
     * @param ps             手机号码集合
     * @param messageContent
     * @return
     */
    private SmsResult Send(List<String> ps, String messageContent) {
        SmsResult res = new SmsResult();
        //短信内容, 最大402个字或字符
        if (402 < messageContent.length()) {
            res.setMsg("短信内容, 最大402个字或字符");
            return res;
        }
        //最多1000个号码
        if (ps.size() > 1000) {
            res.setMsg("最多发送1000个号码");
            return res;
        }
        //手机号码(多个号码用”,”分隔)
        String pStr = String.join(",", ps);

        //流水号
        int i = (int) (Math.random() * 900) + 100;
        String serNo = new Date().toString("yyyyMMddHHmmssS") + i;

        Map<String, String> map = new HashMap<>();
        map.put("SpCode", common.getSms().getSpCode());
        map.put("LoginName", common.getSms().getLoginName());
        map.put("Password", common.getSms().getPassword());
        map.put("MessageContent", messageContent);//messageContent
        map.put("UserNumber", pStr);
        map.put("SerialNumber", serNo);
        map.put("ScheduleTime", "");
        map.put("ExtendAccessNum", "");
        map.put("f", "1");
        String r = OkHttpUtils.post(common.getSms().getUrl(), map, "gbk");
        //result=0&description=发送短信成功&taskid=2051181449018382&faillist=&task_id=2051181449018382
        Map<String, String> result = OkHttpUtils.URLRequest(r);
        String code = MapUtils.getString(result, "result", "-1");
        String msg = MapUtils.getString(result, "description", "-1");
        String taskid = MapUtils.getString(result, "taskid", "-1");
        String faillist = MapUtils.getString(result, "faillist", null);
        String task_id = MapUtils.getString(result, "task_id", "-1");
        log.info("短信返回参数：{}", r);
        log.info("短信发送结果：{}", code);
        log.info("短信返回信息：{}", msg);
        log.info("短信返回taskid：{}", taskid);
        log.info("短信返回faillist：{}", faillist);
        log.info("短信返回task_id：{}", task_id);
        if ("0".equals(code)) {
            res.setSuccess(true);
            res.setMsg("短信发送成功");
            return res;
        }
        res.setMsg(msg);
        return res;
    }

}
